package blog.caidabao.controller;

import blog.caidabao.pojo.Category;
import blog.caidabao.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping
    public ResponseEntity<List<Category>> selectAllCategory(){
       List<Category> categoryList=categoryService.categeryAll();
        if(categoryList==null){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

        }
        return ResponseEntity.ok(categoryList);

    }

    @DeleteMapping("{id}")
    public ResponseEntity<String> categoryDelte(@PathVariable("id") Integer id){
        Boolean result=this.categoryService.categoryDelete(id);
        if (result==true){
            return ResponseEntity.ok("删除成功！");
        }
        return ResponseEntity.ok("删除失败,请确保已无文章与此分类相关联！");
    }

    @PostMapping
    public ResponseEntity<String> categorySave(@RequestParam String newCategoryDesc){
        Category category=new Category();
        category.setCategoryDesc(newCategoryDesc);
        Boolean result=this.categoryService.categorySave(category);
        if (result==true){
            return ResponseEntity.ok("创建成功！");
        }
        return ResponseEntity.ok("创建失败,请确保该分类与旧分类名称不同！");
    }
}
